package com.ews.onlineexchange.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.event.FileUploadEvent;

import com.ews.onlineexchange.model.Attachment;
import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.DeterminedRecord;
import com.ews.onlineexchange.model.RejectRecord;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.UndeterminedRoster;
import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.BulletinService;
import com.ews.onlineexchange.service.DeterminedRecordService;
import com.ews.onlineexchange.service.EntityHome;
import com.ews.onlineexchange.service.RejectRecordHome;
import com.ews.onlineexchange.service.UserService;
import com.ews.onlineexchange.util.AttachmentUtils;

@Named
@ConversationScoped
public class UndeterminedRosterHome extends EntityHome<UndeterminedRoster, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	@Inject
	UserService userService;
	private List<ServiceSupplier> selectedSuppliers;
	
	@Override
	public UndeterminedRoster loadInstance() {
		// TODO Auto-generated method stub
		UndeterminedRoster instance = super.loadInstance();
		selectedSuppliers = instance.getSuppliers();
		return  instance ;
	}

	@Override
	public String saveAndFlush() {
		//当信息被审核通过或被驳回后，不允许进行其他操作
		if(getInstance().getAuditted() != null) {
			FacesContext.getCurrentInstance().addMessage("",new FacesMessage(FacesMessage.SEVERITY_ERROR, "此条信息已经被审核，不能进行修改操作！", ""));
			return null;
		}
		
		if(getInstance().getEvidences().size() == 0) {
			FacesContext.getCurrentInstance().addMessage("evidences",new FacesMessage(FacesMessage.SEVERITY_ERROR, "请至少上传一个证据材料！", ""));
			return null;
		}
		getInstance().setSuppliers(getSelectedSuppliers());
		getInstance().setEnteringDate(new Date());
		User user = userService.getLoginedUser();
		getInstance().setEnteringUser(user);
	
		return super.saveAndFlush();
	}
	
	@Inject
	DeterminedRecordService recordService;
	
	private List<ServiceSupplier> existedSuppliers;
	@Inject
	BulletinService bulletinService;
	public String audit() {
		if(getInstance().getAuditted() != null) {
			FacesContext.getCurrentInstance().addMessage("",new FacesMessage(FacesMessage.SEVERITY_ERROR, "此条信息已经被审核，不能进行修改再次审核！", ""));
			return null;
		}
		getInstance().setAuditted(true);
		getInstance().setAuditDate(new Date());
		getInstance().setAuditUser(userService.getLoginedUser());
		existedSuppliers = new ArrayList<>();
		for (ServiceSupplier serviceSupplier : getInstance().getSuppliers()) {
			if(recordService.isExistSupplierInRecord(serviceSupplier.getId())) {
				existedSuppliers.add(serviceSupplier);
				continue;
			}
			DeterminedRecord record = new DeterminedRecord();
			record.setSupplier(serviceSupplier);
			record.setUndeterminedRoster(getInstance());
			record.setStartDate(getInstance().getStartDate());
			record.setEndDate(getInstance().getEndDate());
			recordService.persisterRecord(record);
		}
		
		String result = super.saveAndFlush();
		if("saved".equals(result)) {
			bulletinService.cancelAppliedTrades(getInstance().getSuppliers());
		}
		return result;
	}
	@Inject
	RejectRecordHome rejectRecordHome;
	public String reject() {
		getInstance().setAuditDate(new Date());
		getInstance().setAuditUser(userService.getLoginedUser());
		getInstance().setAuditted(false);	
		RejectRecord rejectRecord = rejectRecordHome.getInstance();
		getInstance().setRejectRecord(rejectRecord);
		String result = super.saveAndFlush();
		return result;		
	}
	@Inject
	AttachmentUtils attachmentUtils;
	public void uploadEvidence(FileUploadEvent event) {
		if (event.getFile() == null)
			return ;
		
		Attachment attr = attachmentUtils.getAttachmentFromUpload(event.getFile());
		
		getInstance().getEvidences().add(attr);
		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void removeEvidence(Attachment attachment) {
		getInstance().getEvidences().remove(attachment);
	}
	@Inject
	ServiceSupplierManageList serviceSupplierManageList;
	public List<ServiceSupplier> filterSupplier(String query) {
		serviceSupplierManageList.refresh();
		serviceSupplierManageList.setMaxResults(null);
		serviceSupplierManageList.setCnname(query);
        List<ServiceSupplier> suppliers = serviceSupplierManageList.getResultList();
         
        return suppliers;
	  }
	
	@Override
	public String delete() {
		getInstance().setDelFlag(DataEntity.DEL_FLAG_DELETE);
		String result = super.saveAndFlush();
		return result;
	}
	
	public String myDelete() {
		
		
		return "saved";
	}
	
	public List<ServiceSupplier> getSelectedSuppliers() {
		return selectedSuppliers;
	}

	public void setSelectedSuppliers(List<ServiceSupplier> selectedSuppliers) {
		this.selectedSuppliers = selectedSuppliers;
	}
	
	
	
}
